<template>
  <view clas="whe_maxv xd boxs"
        style="padding:10px 20px">
    <up-form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="form1"
        labelWidth="110"
        labelAlign="left"
    >
      <up-form-item
          class="ba_gr"
          label="收货地址:"
          prop="userInfo"
          :borderBottom="true"
          ref="item1"
      >
        <view class="whe_max" @click="addMap" style="min-height: 20px">
          <text v-if="provinceAddress">{{provinceAddress}}</text>
          <text v-if="!provinceAddress">选择地区</text>
        </view>
        <!--        <u&#45;&#45;text @click="category.show = true"-->
        <!--                 :text="provinceAddress!==''?provinceAddress:'选择地区'"></u&#45;&#45;text>-->
      </up-form-item>
      <up-form-item
          label="详细地址:"
          prop="userInfo"
          :borderBottom="true"
          ref="item1">
        <up-input
            v-model="data.address"
            border="none"
        ></up-input>
      </up-form-item>
      <up-form-item
          label="收货人:"
          prop="userInfo"
          :borderBottom="true"
          ref="item1"
      >
        <up-input
            v-model="data.name"
            border="none"
        ></up-input>
      </up-form-item>
      <up-form-item
          label="+86:"
          prop="userInfo"
          :borderBottom="true"
          ref="item1"
      >
        <up-input
            v-model="data.phone"
            border="none"
        ></up-input>
      </up-form-item>
      <up-form-item
          label="地址标签:"
          prop="userInfo"
          :borderBottom="true"
          ref="item1"
      >
        <view class="tag_css fz_12">
          <text :class="tagName == item.name?'tag_xz':'tag_wxz'"
                @click="addTag(item)"
                v-for="(item,index) in addressbq" :key="index">{{ item.name }}</text>
        </view>
      </up-form-item>
      <!--      设置默认地址-->
      <view class="wh_f pad_10_0 boxs">
        <view class="flex_1">
          <view class="fz_14">设置默认地址</view>
          <view class="fz_12 wz_hui mag_t-10">提示会优先使用默认地址</view>
        </view>
        <view
            style="width: 100px">
          <up-switch v-model="checked"></up-switch>
        </view>
      </view>
      <!--      粘贴并识别地址-->
      <view v-if="false" class="pad_10_0 boxs">
        <view class="pad_20 boxs bor_10" style="background-color: #f5f5f5">
          <view style="padding-bottom: 30px">
            <up-input
                border="none"
                placeholder="想要识别的家庭地址，包括名字、联系方式与详细地址"
            ></up-input>
          </view>
          <view class="wz_rigdq fz_14">
            <text @click="pasteContent" style="color: #3a9e5f">粘贴并识地址</text>
          </view>
        </view>

      </view>
    </up-form>

    <u-picker :show="category.show" @confirm="confirmCate"
              @cancel="category.show=false" ref="categoryPicker"
              :loading="category.loading" :columns="category.columns" keyName="name"
              @change="changeCategory"></u-picker>

    <!--    底部按钮-->
    <view class="pm ba_white box_yy" style="width: 100%;height:100px;left: 0;bottom: 0">
      <view class="wh_f he_max jz_flex fz_16">
        <view @click="submitOrder"
              class="jz_flex wz_white bor_25 mag_r-10"
              style="background-color: #3a9e5f;width: 90%;height: 40px">
          <text>保存地址</text>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import {isEmpty} from 'lodash'
import {getRegionByPid, gfReceivesave} from "../../Api/shop";

export default {
  data(){
    return{
      category:{
        show:false,
        loading:false,
        columns:[]
      },
      addressbq:[
        {name:'家'},{name:'公司'},{name:'学校'},{name:'父母'},{name:'朋友'}
      ],
      isMr:true,
      form:{},
      rules:{},
      checked:false,
      provinceAddress:'',
      defaultRegion: ["310000", "310100", "310101"],
      selectedRegion: "", // 用户选择的结果
      // 当前编辑的地址对象
      currentAddress: {
        person: '',
        region: [],
        province: "",
        city: "",
        district: "",
        mobile: '',
        address: '',
        isDefault: 1,
      },
      tagName:'',
      data:{
        id:'',
        name:'',
        phone:'',
        address:'',
        address_all:'',
        is_default:1,
        province_id:0,
        city_id:0,
        county_id:0
      },
      latitude:"",
      longitude:"",
      gps_List:{}
    }
  },
  methods:{
    addMap(){
      let location;
      console.log('我是存储的地址',this.latitude,this.longitude)
      if(this.latitude !=='' && this.longitude !==''){
        console.log('我是获取地址',this.latitude,this.longitude)
        location = JSON.stringify({
          latitude:this.latitude,
          longitude: this.longitude,
        })
      }else{
        // 30.717005 121.016325
        location = JSON.stringify({
          latitude: 30.717005,
          longitude: 121.016325,
        })
      }
      const key = 'VBYBZ-ES7WC-KBC2P-AV5VY-DATI5-76B7B'; //使用在腾讯位置服务申请的key
      const referer = '鲜到家族'; //调用插件的app的名称
      const category = '生活服务,娱乐休闲';
      wx.navigateTo({
        url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`,
      })
    },
    addMaps(){
      var that = this
      let location;
      wx.authorize({
        scope: 'scope.userLocation',//发起定位授权
        success: function () {
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              let latAddress = JSON.stringify({
                latitude : res.latitude,
                longitude : res.longitude
              })
              uni.setStorageSync('latAddress',latAddress);
              location = JSON.stringify({
                latitude: res.latitude,
                longitude: res.longitude
              })
              const key = 'VBYBZ-ES7WC-KBC2P-AV5VY-DATI5-76B7B'; //使用在腾讯位置服务申请的key
              const referer = '鲜到家族'; //调用插件的app的名称
              const category = '生活服务,娱乐休闲';
              wx.navigateTo({
                url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`,
              })
              const chooseLocation = requirePlugin('chooseLocation');
              location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
              console.log('输出位置',location)
              // that.provinceAddress = location.city + location.district + location.name
            }
          })
          //授权成功，此处调用获取定位函数
        }, fail() {
          //如果用户拒绝授权，则要告诉用户不授权就不能使用，引导用户前往设置页面。
          console.log('没有定位授权')
          wx.showModal({
            cancelColor: 'cancelColor',
            title: '没有授权无法获取位置信息',
            content: '是否前往设置页面手动开启',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  withSubscriptions: true,
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '您取消了定位授权',
                })
              }
            }, fail: function (e) {
              location = JSON.stringify({
                latitude: 39.89631551,
                longitude: 116.323459711,
              })
              const key = 'VBYBZ-ES7WC-KBC2P-AV5VY-DATI5-76B7B'; //使用在腾讯位置服务申请的key
              const referer = '鲜到家族'; //调用插件的app的名称
              const category = '生活服务,娱乐休闲';
              wx.navigateTo({
                url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`,
              });
              console.log(e)
            }
          })
        }
      })
    },
    addTag(e){
      this.tagName=e.name;
      this.data.tag=e.name;
    },
    changeCategory(e){
      this.data.province = e.value[0].name
      this.data.city = e.value[1].name
      this.data.county = e.value[2].name
      console.log(777888,this.data)
      const {
        columnIndex,
        value,
        values,
        index,
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs.categoryPicker
      } = e
      this.category.loading = true
      if (columnIndex === 0) {
        let id = value[0].id
        getRegionByPid({pid:id}).then(res =>{
          picker.setColumnValues(1, res.data)
          getRegionByPid({pid:res.data[0].id}).then(res2 => {
            picker.setColumnValues(2, res2.data)
          })
        })
      }else if(columnIndex === 1){
        let id = value[1].id
        getRegionByPid({pid:id}).then(res =>{
          picker.setColumnValues(2, res.data)
        })
      }
      this.category.loading = false
    },
    confirmCate(e){
      // if(_.isEmpty(e.value[2])){
      //   uni.showToast({
      //     icon:'none',
      //     title:'请选择区'
      //   })
      //   return
      // }
      this.data.province_id = e.value[0].id
      this.data.city_id = e.value[1].id
      this.data.county_id = e.value[2].id
      this.provinceAddress = e.value[0].name+e.value[1].name+e.value[2].name
      this.category.show = false
    },
    onRegionChange(e) {
      console.log(777,e.detail.value)
      this.currentAddress.region = e.detail.value;
      this.selectedRegion = e.detail.value.join("-"); // 获取选择的省市区
    },
    isPhone(value){
      return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value);
    },
    submitOrder(){
      //默认地址的开关
      this.data.is_default = this.checked?1:0
      console.log('提交的地址信息',this.data)
      if(!this.isPhone(this.data.phone)){
        uni.showToast({
          icon:'none',
          title:'请输入正确的手机号'
        })
        return
      }
      if(this.provinceAddress === ''){
        uni.showToast({
          icon:'none',
          title:'所在地区必须'
        })
      }else{
        gfReceivesave(this.data).then(res =>{
          if(res.success){
            uni.showToast({
              icon:'none',
              title:'保存成功'
            })
            uni.navigateBack({
              delta: 1 // 返回的页面数，1表示返回上一页，2表示返回上上页，以此类推
            });
          }
        })
      }
    },
  },
  onShow(){
    // 监听地图选点
    const chooseLocation = requirePlugin('chooseLocation');
    const location = chooseLocation.getLocation();
    if (location) {
      this.provinceAddress = location.address;
      console.log('输出位置', location);
      this.data.latitude = location.latitude
      this.data.longitude = location.longitude
      this.data.address_all = location.address
      // 清空存储的位置（避免下次进入时获取旧数据）
      chooseLocation.setLocation(null);
    }

    let tthis = this
    wx.authorize({
      scope: 'scope.userLocation',//发起定位授权
      success: function () {
        wx.getLocation({
          type: 'wgs84',
          success(res) {
            tthis.latitude = res.latitude
            tthis.longitude = res.longitude
            console.log('位置123',tthis.latitude,tthis.longitude)
          }
        })
        //授权成功，此处调用获取定位函数
      }, fail() {
        //如果用户拒绝授权，则要告诉用户不授权就不能使用，引导用户前往设置页面。
        console.log('没有定位授权')
        wx.showModal({
          cancelColor: 'cancelColor',
          title: '没有授权无法获取位置信息',
          content: '是否前往设置页面手动开启',
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                withSubscriptions: true,
              })
            } else {
              wx.showToast({
                icon: 'none',
                title: '您取消了定位授权',
              })
            }
          }, fail: function (e) {
            console.log(e)
          }
        })

      }
    })
  },
  onLoad(options){
    console.log('options?',options)
    if(options?.data){
      let data = options.data
      this.data =JSON.parse(data)
      this.tagName = this.data.tag
      this.checked = this.data.is_default == 1?true:false
      this.provinceAddress = this.data.address_all
    }
  },
  mounted() {
    // getRegionByPid().then(res => {
    //   this.category.columns.push(res.data)
    //   getRegionByPid({pid:res.data[0].id}).then(res2 => {
    //     this.category.columns.push(res2.data)
    //     getRegionByPid({pid:res2.data[0].id}).then(res3 => {
    //       res3.data.unshift({name:'',id:0})
    //       this.category.columns.push(res3.data)
    //     })
    //   })
    // })
  },
}
</script>
<style scoped lang="scss">

.region_select {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tag_xz{
  background-color: #d5f0dd;
  color: #3a9e5f;
  padding: 2px 5px;
  margin-left: 10px;
  border-radius: 5px;
}
.tag_wxz{
  padding: 2px 5px;
  background-color: #f5f5f5;
  color: #4b4b4b;
  margin-left: 10px;
  border-radius: 5px;
}
</style>
